using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace BilSimser.SharePoint.Common.Controls
{
	public class OWSChoiceField : OWSBase
	{
		#region construction

		/// <summary>
		/// Default constructor
		/// </summary>
		public OWSChoiceField()
		{
		}

		#endregion

		#region internal members

		private ListItemCollection _items = new ListItemCollection();

		#endregion

		#region public properties

		/// <summary>
		/// Indicates the choice format of the display
		/// </summary>
		public SPChoiceFormatType ChoiceFormat
		{
			get
			{
				if (ViewState["ChoiceFormat"] == null)
					ChoiceFormat = SPChoiceFormatType.Dropdown;
				return (SPChoiceFormatType) ViewState["ChoiceFormat"];
			}
			set { ViewState["ChoiceFormat"] = value; }
		}

		/// <summary>
		/// Gets the list items. 
		/// </summary>
		public ListItemCollection Items
		{
			get { return _items; }
		}

		#endregion

		#region overridden properties

		/// <summary>
		/// Gets the text of the selected item.
		/// </summary>
		public override string Text
		{
			get
			{
				ListItem item = null;
				for (int x = 0; x < Items.Count && item == null; x++)
				{
					if (Items[x].Value == Value)
						item = Items[x];
				}
				if (item == null)
					return "";
				return item.Text;
			}
		}

		#endregion

		#region overridden methods

		/// <summary>
		/// Renders the OWS Control
		/// </summary>
		/// <param name="wtr">writes out the text control information</param>
		protected override void Render (HtmlTextWriter wtr)
		{
			wtr.Write(
				"<SCRIPT>" +
					"fld = new ChoiceField(frm, \"{0}\", \"{1}\", \"{2}\");" +
					"fld.format = \"{3}\";" +
					"{4};" +
					"fld.fRequired = {5};" +
					"fld.IMEMode=\"\";" +
					"fld.BuildUI();" +
					"</SCRIPT>",
				UniqueID,
				Display,
				JavaScriptValue,
				ChoiceFormat.ToString(),
				GetChoicesJScript(),
				Required.ToString().ToLower()
				);
		}

		#endregion

		#region helper methods

		/// <summary>
		/// Gets the javascript to add choice to the end user. 
		/// </summary>
		/// <returns>the choices javascript</returns>
		private string GetChoicesJScript()
		{
			string ret = "";
			foreach (ListItem item in _items)
			{
				ret += string.Format(
					"fld.AddChoice(\"{0}\",\"{1}\");",
					item.Text.Replace(@"\", @"\\").Replace("\"", "\\\""),
					item.Value.Replace(@"\", @"\\").Replace("\"", "\\\"")
					);
			}
			return ret;
		}

		#endregion
	}
}